#define _CRT_SECURE_NO_WARNINGS 1
#include"sl.h"

SListNode* BuySListNode(SLTDateType x)
{
	SListNode* Newnode = (SListNode*)malloc(sizeof(SListNode));
	Newnode->data = x;
	Newnode->next = NULL;

	return Newnode;
}

void SListPrint(SListNode* plist)
{
	SListNode* cur = plist;
	while (cur)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SListPushBack(SListNode** pplist, SLTDateType x)
{

	SListNode* Newnode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = Newnode;
	}
	else
	{
		SListNode* tail = *pplist;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = Newnode;
	}
}

void SListDestroy(SListNode* plist)
{
	SListNode* cur = plist;
	while (cur)
	{
		SListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	plist = NULL;

}

void SListPushFront(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* Newnode = BuySListNode(x);

	if (*pplist == NULL)
	{
		*pplist = Newnode;
	}
	else
	{
		Newnode->next = *pplist;
		*pplist = Newnode;
	}
}

void SListPopBack(SListNode** pplist)
{
	SListNode* tail = *pplist;
	SListNode* prev = NULL;

	if (tail == NULL || tail->next == NULL)
	{
		free(tail);
		*pplist = NULL;
	}
	else
	{
		while (tail->next)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		tail = NULL;
		prev->next = NULL;
	}
	
}

void SListPopFront(SListNode** pplist)
{
	SListNode* first = *pplist;
	if (first == NULL)
	{
		return;
	}
	else if (first->next == NULL)
	{
		free(first);
		*pplist = NULL;
	}
	else
	{
		SListNode* next = first->next;
		free(first);
		first = NULL;
		*pplist = next;
	}
}

SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	SListNode* cur = plist;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	assert(pos);
	SListNode* Newnode = BuySListNode(x);
	Newnode->next = pos->next;
	pos->next = Newnode;

}

void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	assert(pos->next);
	SListNode* next = pos->next;
	pos->next = next->next;
	free(next);
}